<template>
  <a-modal
    v-model:open="visible"
    title="添加套餐"
    width="800px"
    :footer="null"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
      class="package-form"
    >
      <!-- 套餐基本信息 -->
      <div class="form-section">
        <h3 class="section-title">套餐信息</h3>
        <div class="form-row">
          <div class="form-column">
            <a-form-item label="套餐名称" name="name" required>
              <a-input
                v-model:value="formData.name"
                placeholder="请输入套餐名称"
                size="large"
              />
            </a-form-item>
            <a-form-item label="分类" name="category" required>
              <a-select
                v-model:value="formData.category"
                placeholder="请选择分类"
                size="large"
              >
                <a-select-option value="package">套餐</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="单位" name="unit">
              <a-input
                v-model:value="formData.unit"
                placeholder="请输入单位"
                size="large"
              />
            </a-form-item>
            <a-form-item label="规格" name="specification">
              <a-input
                v-model:value="formData.specification"
                placeholder="请输入规格"
                size="large"
              />
            </a-form-item>
          </div>
          <div class="form-column">
            <a-form-item label="套餐编号" name="code">
              <a-input
                v-model:value="formData.code"
                placeholder="请输入套餐编号"
                size="large"
              />
            </a-form-item>
            <a-form-item label="套餐条码" name="barcode">
              <a-input
                v-model:value="formData.barcode"
                placeholder="请输入套餐条码"
                size="large"
              />
            </a-form-item>
            <a-form-item label="说明" name="description">
              <a-textarea
                v-model:value="formData.description"
                placeholder="请输入套餐说明"
                :rows="3"
              />
            </a-form-item>
          </div>
        </div>
      </div>

      <!-- 套餐项目 -->
      <div class="form-section">
        <div class="section-header">
          <h3 class="section-title">套餐项目</h3>
          <div class="total-price">合计: ¥{{ totalPrice.toFixed(2) }}</div>
        </div>

        <div class="package-items">
          <div class="items-header">
            <a-button type="primary" @click="showAddItemModal">
              <template #icon><Plus /></template>
              添加项目
            </a-button>
          </div>

          <a-table
            :columns="itemColumns"
            :data-source="formData.items"
            :pagination="false"
            size="small"
            row-key="id"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'totalPrice'">
                ¥{{ (record.unitPrice * record.quantity).toFixed(2) }}
              </template>
              <template v-else-if="column.key === 'action'">
                <a-button
                  type="link"
                  size="small"
                  danger
                  @click="removeItem(index)"
                >
                  <template #icon><Trash2 /></template>
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>

        <div class="package-note">
          <p class="note-text">
            可修改套餐内商品价格,以实现套餐价格修改,打印小票时只显示套餐价,不显示其中具体商品价格
          </p>
        </div>
      </div>
    </a-form>

    <!-- 操作按钮 -->
    <div class="modal-footer">
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="saving" @click="handleSave">
          保存
        </a-button>
        <a-button
          type="primary"
          :loading="saving"
          @click="handleSaveAndContinue"
        >
          保存并继续添加项目
        </a-button>
      </a-space>
    </div>
  </a-modal>
  <!-- 添加项目模态框 -->
  <a-modal
    v-model:open="addItemModalVisible"
    title="添加套餐项目"
    width="600px"
    @ok="handleAddItem"
    @cancel="addItemModalVisible = false"
  >
    <a-form layout="vertical">
      <a-form-item label="选择商品">
        <a-select
          v-model:value="selectedProductId"
          placeholder="请选择商品"
          style="width: 100%"
          show-search
          :filter-option="filterOption"
        >
          <a-select-option
            v-for="product in availableProducts"
            :key="product.id"
            :value="product.id"
          >
            {{ product.name }} - ¥{{ product.unitPrice }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="数量">
        <a-input-number
          v-model:value="selectedQuantity"
          placeholder="请输入数量"
          style="width: 100%"
          :min="1"
          :precision="2"
        />
      </a-form-item>
      <a-form-item label="单价">
        <a-input-number
          v-model:value="selectedUnitPrice"
          placeholder="请输入单价"
          style="width: 100%"
          :min="0"
          :precision="2"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';
import { Plus, Trash2 } from '@vben/icons';

// 定义props
interface Props {
  visible: boolean;
  primaryCategory: string;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  primaryCategory: 'registration',
});

// 定义emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  save: [packageData: any];
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const saving = ref(false);
const addItemModalVisible = ref(false);
const selectedProductId = ref('');
const selectedQuantity = ref(1);
const selectedUnitPrice = ref(0);

// 表单数据
const formData = reactive({
  name: '',
  category: 'package',
  unit: '',
  specification: '',
  code: '',
  barcode: '',
  description: '',
  items: [] as any[],
});

// 表单验证规则
const formRules = {
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
};

// 表格列定义
const itemColumns = [
  {
    title: '项目名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    width: 120,
  },
  {
    title: '单位',
    dataIndex: 'unit',
    key: 'unit',
    width: 80,
  },
  {
    title: '单价(元)',
    dataIndex: 'unitPrice',
    key: 'unitPrice',
    width: 100,
    align: 'right',
  },
  {
    title: '数量',
    dataIndex: 'quantity',
    key: 'quantity',
    width: 80,
    align: 'right',
  },
  {
    title: '总价',
    key: 'totalPrice',
    width: 100,
    align: 'right',
  },
  {
    title: '操作',
    key: 'action',
    width: 80,
  },
];

// 模拟可用商品数据
const availableProducts = ref([
  {
    id: '1',
    name: '拜宠清猫用',
    unitPrice: 25.0,
    specification: '',
    unit: '',
  },
  {
    id: '2',
    name: '福来恩猫用0.5ml',
    unitPrice: 70.0,
    specification: '',
    unit: '',
  },
  {
    id: '3',
    name: '大宠爱猫用',
    unitPrice: 45.0,
    specification: '',
    unit: '',
  },
]);

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const totalPrice = computed(() => {
  return formData.items.reduce((total, item) => {
    return total + item.unitPrice * item.quantity;
  }, 0);
});

// 方法
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    category: 'package',
    unit: '',
    specification: '',
    code: '',
    barcode: '',
    description: '',
    items: [],
  });
};

const filterOption = (input: string, option: any) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

const showAddItemModal = () => {
  addItemModalVisible.value = true;
  selectedProductId.value = '';
  selectedQuantity.value = 1;
  selectedUnitPrice.value = 0;
};

const handleAddItem = () => {
  if (!selectedProductId.value) {
    message.warning('请选择商品');
    return;
  }

  const product = availableProducts.value.find(
    (p) => p.id === selectedProductId.value,
  );
  if (!product) {
    message.error('商品不存在');
    return;
  }

  const newItem = {
    id: Date.now().toString(),
    name: product.name,
    specification: product.specification,
    unit: product.unit,
    unitPrice: selectedUnitPrice.value || product.unitPrice,
    quantity: selectedQuantity.value,
  };

  formData.items.push(newItem);
  addItemModalVisible.value = false;
  message.success('添加成功');
};

const removeItem = (index: number) => {
  formData.items.splice(index, 1);
  message.success('删除成功');
};

const handleSave = async () => {
  try {
    await formRef.value?.validate();
    saving.value = true;

    // 模拟保存请求
    await new Promise((resolve) => setTimeout(resolve, 1000));

    const packageData = {
      ...formData,
      id: Date.now().toString(),
      code: formData.code || `P${String(Date.now()).padStart(8, '0')}`,
      primaryCategory: props.primaryCategory,
      primaryCategoryprimaryCategory,
    };

    emit('save', packageData);
    message.success('保存成功');
    visible.value = false;
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    saving.value = false;
  }
};

const handleSaveAndContinue = async () => {
  try {
    await formRef.value?.validate();
    saving.value = true;

    // 模拟保存请求
    await new Promise((resolve) => setTimeout(resolve, 1000));

    const packageData = {
      ...formData,
      id: Date.now().toString(),
      code: formData.code || `P${String(Date.now()).padStart(8, '0')}`,
      primaryCategory: props.primaryCategory,
      primaryCategoryprimaryCategory,
    };

    emit('save', packageData);
    message.success('保存成功');

    // 重置表单继续添加
    resetForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  } finally {
    saving.value = false;
  }
};

const handleCancel = () => {
  visible.value = false;
};

// 监听props变化，初始化表单数据
watch(
  () => props.visible,
  (newVisible) => {
    if (newVisible) {
      resetForm();
    }
  },
);
</script>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
    gap: 16px;
  }

  .section-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}

.package-form {
  max-height: 70vh;
  overflow-y: auto;
}

.form-section {
  margin-bottom: 24px;
}

.section-title {
  padding-bottom: 8px;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e8e8e8;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.total-price {
  font-size: 18px;
  font-weight: 600;
  color: #1890ff;
}

.form-row {
  display: flex;
  gap: 24px;
}

.form-column {
  flex: 1;
  min-width: 0;
}

.package-items {
  margin-bottom: 16px;
}

.items-header {
  margin-bottom: 16px;
}

.package-note {
  padding: 12px;
  background: #fff2e8;
  border: 1px solid #ffbb96;
  border-radius: 4px;
}

.note-text {
  margin: 0;
  font-size: 14px;
  color: #d46b08;
}

.modal-footer {
  padding-top: 16px;
  margin-top: 24px;
  text-align: right;
  border-top: 1px solid #e8e8e8;
}
</style>
